package com.zxj.transfer.bank2.service;

import com.google.common.collect.Lists;
import com.zxj.transfer.api.service.Bank2Service;
import com.zxj.transfer.orm.service.TCancelLogService;
import com.zxj.transfer.orm.service.TConfirmLogService;
import com.zxj.transfer.orm.service.TTryLogService;
import com.zxj.transfer.orm.service.UserAccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.dromara.hmily.annotation.HmilyTCC;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;

@Slf4j
@DubboService(version = "1.0.0", tag = "red", weight = 100)
public class Bank2ServiceImpl implements Bank2Service {

    @Autowired
    private TTryLogService tryLogService;
    @Autowired
    private TConfirmLogService confirmLogService;
    @Autowired
    private TCancelLogService cancelLogService;
    @Autowired
    private UserAccountService userAccountService;

    @Override
    @HmilyTCC(confirmMethod = "confirm", cancelMethod = "cancel")
    public void changeRmb(String tid, Integer userIdA, BigDecimal usAccount, Integer userIdB, BigDecimal rmbAccount) {
        log.info("Bank2ServiceImpl.changeRmb执行");
        if (tryLogService.isExist(tid)) {
            return;
        }
        if (confirmLogService.isExist(tid) || cancelLogService.isExist(tid)) {
            return;
        }
//        // 模拟异常情况
//        try {
//            Thread.sleep(10000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        Lists.newArrayList().get(1);
        // 冻结人民币，插入try日志
        userAccountService.subtractRmbAccount(userIdB, tid, rmbAccount);
    }

    public void confirm(String tid, Integer userIdA, BigDecimal usAccount, Integer userIdB, BigDecimal rmbAccount) {
        log.info("Bank2ServiceImpl.confirmRmb执行");
        if (!confirmLogService.isExist(tid)) {
            if (tryLogService.isExist(tid) && !cancelLogService.isExist(tid)) {
                userAccountService.confirmSubtractRmbAccount(userIdB, tid, usAccount);
            }
        }
    }

    public void cancel(String tid, Integer userIdA, BigDecimal usAccount, Integer userIdB, BigDecimal rmbAccount) {
        log.info("Bank2ServiceImpl.cancelRmb执行");
        if (!cancelLogService.isExist(tid)) {
            if (tryLogService.isExist(tid) && !confirmLogService.isExist(tid)) {
                if (confirmLogService.isExist(tid)) {
                    userAccountService.cancelSubtractRmbAccountConfirm(userIdB, tid, usAccount, rmbAccount);
                } else {
                    userAccountService.cancelSubtractRmbAccountNoConfirm(userIdB, tid, rmbAccount);
                }
            }
        }
    }
}
